package com.yaoayao.mall.order.consumer;

import com.alibaba.fastjson.JSONObject;
import com.yaoayao.mall.model.enums.ProcessStatus;
import com.yaoayao.mall.order.service.OrderInfoService;
import com.yaoayao.mall.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: 李旭
 * @Time: 11:20
 * @Description:
 *
 *   减库存
 */
@Component
public class DecrStockConsumer {


    @Autowired
    private OrderInfoService orderInfoService;
    //减库存  也需要 更新订单状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = MqConst.ROUTING_WARE_ORDER
    ))
    public void decrStockAndUpdateOrderStatus(String jsonMap, Message message, Channel channel){
        try {
        /*    Map<String, Object> map = new HashMap<>();
            map.put("orderId", wareOrderTask.getOrderId());
            map.put("status", wareOrderTask.getTaskStatus().toString());*/
            Map map = JSONObject.parseObject(jsonMap, Map.class);
            //判断减库存是否成功
            if("DEDUCTED".equals(map.get("status"))){
                //成功了
                //更新订单状态
                orderInfoService.updateOrderStatus(Long.parseLong(String.valueOf(map.get("orderId"))),
                        ProcessStatus.WAITING_DELEVER);
            }else{
                //异常了
                //打印日志
                //更新订单状态
                orderInfoService.updateOrderStatus(Long.parseLong(String.valueOf(map.get("orderId"))),
                        ProcessStatus.STOCK_EXCEPTION);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
